package 设置占有锁的时间;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: ywk
 * @date: 2020-09-26
 */
public class OccupyLock {
    static AtomicInteger count = new AtomicInteger(0);
    static volatile boolean stop = true;
    static final int maxTime = 6;
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        startThread();
    }

    public static void startThread() {
        new Thread(() -> runMethod(10), "thread1").start();
        new Thread(() -> runMethod(5), "thread2").start();

    }

    public static void runMethod(int runTime) {
        int i = runTime;
        lock.lock();
        stop = false;
        Thread daemonThread = new Thread(() -> countMethod(lock));
        daemonThread.setDaemon(true);
        daemonThread.start();

        while (i > 0 && !stop) {
            //业务运行
            System.out.println(Thread.currentThread().getName() + "\t" + "开始倒计时" + i--);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
        if (lock.isLocked()) {
            lock.unlock();
        }
    }

    public static synchronized void countMethod(ReentrantLock lock) {
        while (!stop) {
            if (count.addAndGet(1) > maxTime && lock.isLocked()) {
                count.set(0);
                stop = true;
                throw new RuntimeException("占有超时");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public void getLock() {
        new Thread(() -> {
            int i = 0;
            lock.lock();
            while (i <= 3) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(++i);

            }
            lock.unlock();
        }).start();
        new Thread(() -> {
            try {
                boolean flag = lock.tryLock(5, TimeUnit.SECONDS);
                if (!flag) {
                    System.out.println("获取锁失败");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();
    }
}
